extends Node2D
class_name EnemyHealthComponent
signal die
signal boss_hp_change
signal hurt
signal on_first_half_hp

@export var is_boss: bool = true
var first_half_hp = false
var stats: PandoraEntity
var buff_manager: BuffManager
var _health: float = 0.0
var health: float:
	get:
		return _health
	set(value):
		_health = value
		if is_boss:
			EventBus.push_event("boss_hp_change", [_health, stats.get_float("max_health")])
		
func _ready() -> void:
	await owner.ready
	stats = owner.get_stats()
	health = stats.get_float("max_health")
	
	# 初始化buff管理器
	buff_manager = BuffManager.new()
	add_child(buff_manager)

func damage(attack: float, damage_color: Color = Color.RED, is_critical: bool = false) -> void:
	# 检查是否处于无敌状态
	if owner.has_method("is_invincible_state") and owner.is_invincible_state():
		# 无敌状态下显示"免疫"而不是直接返回
		Utils.show_hit_label_c("免疫", get_parent(), Color.GRAY, false)
		return  # 无敌状态下忽略伤害
	
	print(attack)
	var final_damage = (attack - stats.get_float("defense")) # 计算最终伤害
	## 伤害大于0时
	if final_damage > 0:
		Utils.show_hit_label_c(final_damage, get_parent(), damage_color, is_critical)
	health -= final_damage
	boss_hp_change.emit()
	hurt.emit()
	if health < 0:
		print("死亡")
		die.emit()
		
	if health < stats.get_float("max_health") / 2 and not first_half_hp:
		on_first_half_hp.emit()
		first_half_hp = true
